package be.ipl.finito.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.finito.domaine.Joueur;
import be.ipl.finito.exceptions.BizException;
import be.ipl.finito.usecases.GestionJoueurs;

@SuppressWarnings("serial")
@WebServlet(name = "inscription.html")
public class Inscription extends HttpServlet implements Servlet {

	@EJB
	private GestionJoueurs gj;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher rd = getServletContext().getNamedDispatcher(
				"Inscription");
		rd.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String pseudo = req.getParameter("pseudo");
		String nom = req.getParameter("nom");
		String prenom = req.getParameter("prenom");
		String mdp = req.getParameter("mdp");
		String repeterMdp = req.getParameter("repeterMdp");
		String email = req.getParameter("email");
		try {
			Joueur joueur = gj.inscrireUtilisateur(pseudo, nom, prenom,
					mdp, repeterMdp, email);
			HttpSession session = req.getSession();
			synchronized (session) {
				session.setAttribute("joueur", joueur);
			}
			resp.sendRedirect("choix.html");
			return;
		} catch (BizException e) {
			req.setAttribute("pseudo", pseudo);
			req.setAttribute("nom", nom);
			req.setAttribute("prenom", prenom);
			req.setAttribute("mdp", mdp);
			req.setAttribute("repeterMdp", repeterMdp);
			req.setAttribute("email", email);
			req.setAttribute("messageErreur", e.getMessage());
			doGet(req, resp);
		}
	}
}
